<template>
    <div style="background-color:#FAFAFA;height:100%">

        <el-row class="loginRow" type="flex" justify="center">

            <el-col :span="6">
                <h2 style="text-align:center;">海宝百科</h2>
                <el-image :src='require("@/assets/logo.png")' style="height:180px;width:200px;"></el-image>
            </el-col>

            <el-col style="padding-top:30px" :span="1">
                <el-divider class="loginDivider" direction='vertical'></el-divider>
            </el-col>

            <el-col :span="6">

                <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="loginForm.username"></el-input>
                    </el-form-item>
 
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="loginForm.password" type="password"></el-input>
                    </el-form-item>
                    
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
                        <el-button @click="resetForm('loginForm')">重置</el-button>
                    </el-form-item>
                </el-form>

            </el-col>

        </el-row>
        
    </div>
</template>

<script>
import request from '@/api/client'

export default {
    name: 'Login',
    data() {
        return {

            loginForm: {
                username: '',
                password: ''
            },

            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ],
                
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ]

            }

        }
    },

    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            request.login(this.loginForm).then(resp => {
                const jwt = resp.headers['authorization'];
                localStorage.setItem("username", this.loginForm.username)
                this.$store.commit('SET_TOKEN', jwt)
                // this.$router.push('/')
                this.$router.go(-1)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }

}
</script>

<style>

.loginDivider {
    height: 200px;
}

.loginRow {
    height: 100%;
    display: flex;
    align-items: center;
    text-align: center;
}

</style>